import { fileURLToPath, URL } from 'node:url'
import { BuildOptions, defineConfig, UserConfig, UserConfigExport } from 'vite'
import { type ConfigEnv, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import ReactivityTransform from '@vue-macros/reactivity-transform/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { resolve, join } from 'path'
import glob from 'glob'
import viteCompression from 'vite-plugin-compression'

// import { VitePWA } from 'vite-plugin-pwa'
import dayjs from 'dayjs'

console.debug(`fileURLToPath(new URL('./src', import.meta.url))`, fileURLToPath(new URL('./src', import.meta.url)))

const assetsPath = (path: string) => {
  return join('static', path)
}

const getEntryPath = () => {
  const pageEntry = {} as { [entryAlias: string]: string }
  glob.sync('./src/pages/**/index.html').forEach((entry: string) => {
    const pathArr: string[] = entry.split('/')
    const name: string = pathArr[pathArr.length - 2]
    const namevalue = join(process.cwd(), `/src/pages/${name}/index.html`)
    pageEntry[name] = namevalue
  })
  delete pageEntry.pages
  // main存在,index就多余了
  delete pageEntry.index
  // 该页面和index/html 引用的js是一样的
  pageEntry['main'] = join(process.cwd(), `/src/pages/index.html`)
  console.dir('entry+++++++++++')
  console.dir(pageEntry)
  console.dir('entry----------')
  return pageEntry
}

// https://vitejs.dev/config/
// export default defineConfig(
// 记录Vite项目多页面应用模式踩坑 https://www.xjx100.cn/news/171534.html?action=onClick
/** 配置项文档：https://cn.vitejs.dev/config */
export default defineConfig((configEnv: ConfigEnv) => {
  const version = new Date()
  const packagev = process.env.npm_package_version || 'unknow'
  const root = './src/pages'
  console.log(`process.cwd() is`, process.cwd())

  console.log('configEnv.mode is', configEnv.mode)
  // console.log('env path ', join(process.cwd(), root))

  const viteEnv = loadEnv(configEnv.mode, join(process.cwd()))
  console.log(viteEnv)

  // const { VITE_PUBLIC_PATH } = viteEnv

  console.log(`process.env.ENV_VARIABLE`, process.env.npm_package_version)

  return {
    // envDir: join(process.cwd(), root),
    envDir: join(process.cwd()), // 绝对路径
    envPrefix: 'VITE_',
    root: root,
    base: '/',
    plugins: [
      vue(),
      // 可能会导致白屏
      // VitePWA({
      //   mode: configEnv.mode as'development' | 'production',
      //   manifest: {
      //     name: 'pwd应用名称',
      //     short_name: 'pwd测',
      //     description: 'pwd应用功能描述'
      //   },
      //   registerType: 'autoUpdate',
      //   workbox: {
      //     clientsClaim: true,
      //     skipWaiting: true
      //   },
      //   devOptions: {
      //     enabled: true  // 并不会在开发模式下提示你安装
      //   }
      // }),
      // mpaPlugin({
      //   pages: getEntryPages(),
      //   historyApiFallback: {
      //     rewrites: getRewrites()
      //   }
      // }),
      // gzip压缩 生产环境生成 .gz 文件
      viteCompression({
        verbose: true,
        disable: true,
        threshold: 10240,
        algorithm: 'gzip',
        ext: '.gz'
      }),
      // 支持在jsx中使用注解
      vueJsx({ babelPlugins: [['@babel/plugin-proposal-decorators', { legacy: true }]] }),
      AutoImport({
        // imports: ['vue', 'vue-router', 'pinia'], // 自动导入vue和vue-router相关函数(只有组件里哦，ts或js文件里面不行～～～)
        dts: join(process.cwd(), 'src/types/auto-import.d.ts') //生成全局引入的文件
      })
      // ReactivityTransform()
    ],
    define: {
      'process.env': {
        buildVersion: new Date().toLocaleString(),
        npm_package_version: process.env.npm_package_version,
        publicPath: process.env.NODE_ENV === 'production' ? '/backend/' : '/',
        'clientversion ': JSON.stringify(packagev),
        'version ': JSON.stringify(dayjs(version).format('YYYY-MM-DD HH:mm:ss'))
      },
      'import.meta.env.npm_package_version': JSON.stringify(process.env.ENV_VARIABLE)
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      // host: 'localhost',        // 只能localhost和127.0.0.1访问
      // https: false,
      // host: '0.0.0.0',        //
      /** 设置 host: true 才可以使用 Network 的形式，以 IP 访问项目 */
      host: true, //
      port: 12345, // 端口
      /** 是否自动打开浏览器 */
      open: false,
      /** 跨域设置允许 */
      cors: true,
      strictPort: false, // 若端口已被占用,尝试下移一格端口
      proxy: {
        '/gateway': {
          target: process.env.VITE_API_URL || 'https://pinzhi.xxx.com',
          ws: true,
          changeOrigin: true,
          headers: {
            origin: 'http://localhost'
          },
          rewrite: (path) => path.replace(/^\/gateway/, '')
        }
        // ,'/': {
        //   target: 'http://localhost:8128',
        //   rewrite: () => '/index/index.html',
        // },
      }
    },
    /** 混淆器 */
    esbuild: {
      /** 打包时移除 console.log */
      pure: ['console.log'],
      /** 打包时移除 debugger */
      drop: ['debugger'],
      /** 打包时移除所有注释 */
      legalComments: 'none'
    },
    build: {
      outDir: resolve(process.cwd(), 'build'), // 指定输出路径（相对于 项目根目录)
      sourcemap: false, // 构建后是否生成 source map 文件
      chunkSizeWarningLimit: 2048, // 规定触发警告的 chunk(文件块) 大小2048kb
      assetsDir: 'static', // css js 放到static目录下
      minify: 'esbuild',
      cssCodeSplit: false, // css 是否拆分
      // 10k以下转成base64
      assetsInlineLimit: 1024 * 10,
      rollupOptions: {
        // 自定义底层的 Rollup 打包配置
        input: getEntryPath()
        // output: {
        //   entryFileNames: assetsPath('js/[name].[hash].js'),
        //   chunkFileNames: assetsPath('js/[name].[hash].js'),
        //   assetFileNames: assetsPath('css/[name].[hash].[ext]'),
        //   compact: true,
        //   manualChunks: (id: string) => {
        //     if (id.includes('node_modules')) {
        //       return id.toString().split('node_modules/')[1].split('/')[0].toString() // 拆分多个vendors
        //     }
        //   }
        // }
        // build.rollupOptions.external
      },
      emptyOutDir: true
    }
  }
  // as UserConfigExport
  // as unknown as UserConfigExport

  // console.log('resultExport', resultExport.build.rollupOptions.output)

  // as UserConfig
  // as UserConfigExport
})
